package com.wanmait.employment.interceptor;//package com.wanmait.employment.interceptor;//package com.wanmait.recruitment.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.employment.entity.Admin;
import com.wanmait.employment.entity.Company;
import com.wanmait.employment.entity.Userinfo;
import com.wanmait.employment.service.AdminService;
import com.wanmait.employment.util.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private AdminService adminService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预检请求放行
        //获得请求方式GET POST DELETE OPTIONS...
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //获得token 通过请求头
        String token = request.getHeader("token");
        if (token == null) {
            throw new JWTVerificationException("没有携带令牌token");
        }
        //获得签发对象id
/*        Integer id = Integer.parseInt(JWTUtils.getAudience(token));
        //获得admin
        Admin admin = adminService.getById(id);
        if (admin == null) {
            throw new JWTVerificationException("没有找到管理员，验证失败");
        }
        //验证token
        JWTUtils.verifyToken(token,admin.getPassword());*/
        Admin admin = (Admin)redisTemplate.opsForValue().get(token);
        Company company=(Company) redisTemplate.opsForValue().get(token);
        Userinfo userinfo=(Userinfo) redisTemplate.opsForValue().get(token);

        if(admin==null&&company==null&&userinfo==null){
            throw new JWTVerificationException("没有找到此用户，验证失败");
        }else if(company!=null&&userinfo==null&&admin==null){
            JWTUtils.verifyToken(token,company.getCompanyPassword());
            request.setAttribute("company",company);
        }else if(company==null&&userinfo!=null&&admin==null){
            JWTUtils.verifyToken(token,userinfo.getUserpass());
            request.setAttribute("userinfo",userinfo);
        }else if(company==null&&userinfo==null&&admin!=null){
            JWTUtils.verifyToken(token,admin.getAdminPass());
            request.setAttribute("admin",admin);
        }
        //验证token
        JWTUtils.verifyToken(token,admin.getAdminPass());
        //在后续的控制器中如果使用admin可以直接从request中获取，否则需要通过token获得id再次查询
        request.setAttribute("admin",admin);
        return true;
    }
}